package com.donghua.service;

import com.donghua.controller.UserController;
import com.donghua.dao.DiscussPostMapper;
import com.donghua.dao.DiscussPostTagMapper;
import com.donghua.dao.PictureMapper;
import com.donghua.dao.TagMapper;
import com.donghua.entity.*;
import com.donghua.util.CommunityUtil;
import com.donghua.util.HostHolder;
import com.donghua.util.Result;
import com.donghua.util.SensitiveFilter;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.HtmlUtils;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import static com.donghua.enums.StatusCodeEnum.*;
import static com.donghua.enums.StatusCodeEnum.SUCCESS;

@Service
public class DiscussPostService {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private DiscussPostMapper discussPostMapper;

    @Autowired
    private SensitiveFilter sensitiveFilter;

    @Autowired
    private TagMapper tagMapper;

    @Autowired
    private DiscussPostTagMapper discussPostTagMapper;

    @Autowired
    private PictureMapper pictureMapper;

    @Value("${community.path.upload}")
    private String uploadPath;

    @Value("${community.path.domain}")
    private String domain;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private DiscussPostService discussPostService;

    public List<DiscussPost> findDiscussPosts(int userId, int offset, int limit) {
        return discussPostMapper.selectDiscussPosts(userId, offset, limit);
    }

    public int findDiscussPostRows(int userId) {
        return discussPostMapper.selectDiscussPostRows(userId);
    }

    public int addDiscussPost(DiscussPost post) {
        //注意插入后返回post的id
        if (post == null) {
            throw new IllegalArgumentException("帖子不能为空!");
        }

        // 转义HTML标记
        post.setTitle(HtmlUtils.htmlEscape(post.getTitle()));
        post.setContent(HtmlUtils.htmlEscape(post.getContent()));
        // 过滤敏感词
        post.setTitle(sensitiveFilter.filter(post.getTitle()));
        post.setContent(sensitiveFilter.filter(post.getContent()));

        discussPostMapper.insertDiscussPost(post);
        return post.getId();
    }

    public int addTag(Tag tag) {
        //注意返回tag的id
        if(tag == null) {
            throw new IllegalArgumentException("标签不能为空！");
        }
        tag.setTagName(HtmlUtils.htmlEscape(tag.getTagName()));
        tag.setTagName(sensitiveFilter.filter(tag.getTagName()));
        tagMapper.insertTag(tag);
        return tag.getId();
    }

    public List<String> getDiscussPostTags(int postId) {
        return discussPostTagMapper.selectTagsByDiscussPostId(postId);
    }

    public int addDiscussPostTag(DiscussPostTag discussPostTag) {

        return discussPostTagMapper.insertDiscussPostTag(discussPostTag);
    }

    public DiscussPost findDiscussPostById(int id) {
        return discussPostMapper.selectDiscussPostById(id);
    }

    public List<DiscussPost> findDiscussPostsByUserId(int userId, int offset, int limit) {
        return discussPostMapper.selectDiscussPostsByUserId(userId, offset, limit);
    }

    public int updateCommentCount(int id, int commentCount) {
        return discussPostMapper.updateCommentCount(id, commentCount);
    }

    public int findTagCountByTagName(String tagName) {
        return tagMapper.selectTagCountByTagName(tagName);
    }

    public Tag findTagByTagName(String tagName) {
        return tagMapper.selectTagByTagName(tagName);
    }

    public int updateTagCountByTagName(String tagName) {
        return tagMapper.updateTagCountByTagName(tagName);
    }

    public List<String> findTagsByDiscussPostId(int postId) {
        return discussPostTagMapper.selectTagsByDiscussPostId(postId);
    }

    public List<Integer> findHotTagId(int offset, int limit) {
        return tagMapper.selectHotTagId(offset, limit);
    }

    public Tag findTagById(int id) {
        return tagMapper.selectTagById(id);
    }

    public List<Integer> findPostIdByTagId(int tagId, int offset, int limit) {
        return discussPostTagMapper.selectHotPostId(tagId, offset, limit);
    }

    public int findTagIdByTagName(String tagName) {
        return tagMapper.seletTagIdByTagName(tagName);
    }

    public int addPicture(Picture picture) {
        return pictureMapper.insertPicture(picture);
    }

    public List<Picture> findPicturesByPostId(int postId) {
        return pictureMapper.selectPicturesByPostId(postId);
    }

    public Result<?> uploadPicture(MultipartFile file, Picture picture) {
        if (file == null) {
            return Result.ok(NO_SELECTED_PICTURE.getCode(), NO_SELECTED_PICTURE.getMsg());
        }

        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        if (StringUtils.isBlank(suffix)) {
            return Result.ok(FILE_FORMAT_ERROR.getCode(), FILE_FORMAT_ERROR.getMsg());
        }

        // 生成随机文件名
        fileName = CommunityUtil.generateUUID() + suffix;
        // 确定文件存放的路径
        File upload = new File(uploadPath);
        if(!upload.exists()) {
            upload.mkdirs();
        }
        File dest = new File(uploadPath + "/" + fileName);
        try {
            // 存储文件
            file.transferTo(dest);
        } catch (IOException e) {
            logger.error("上传文件失败: " + e.getMessage());
            throw new RuntimeException("上传文件失败,服务器发生异常!", e);
        }
        // 更新当前用户的图片的路径(web访问路径)
        // http://localhost:8081/users/image/xxx.png
        User user = hostHolder.getUser();
        String pictureUrl = domain + contextPath + "/users/image/" + fileName;
        picture.setCreateTime(new Date());
        picture.setPictureUrl(pictureUrl);
        discussPostService.addPicture(picture);

        return Result.ok(SUCCESS.getCode(), SUCCESS.getMsg());
    }
}
